<?php
namespace Home\Controller;
use Think\Controller;
class ServiceController extends Controller {
	public function index(){
		if (!$weObj =getCache('weObj')) {
			$options = array(
			   'token' => c('wxtoken'), 				//填写你设定的key
			   'encodingaeskey'=>c('encodingaeskey'), 	//填写加密用的EncodingAESKey
			   'appid'=>c('appid'), 					//填写高级调用功能的app id, 请在微信开发模式后台查询
			   'appsecret'=>c('appsecret') 				//填写高级调用功能的密钥
			   );
			$weObj = new \Org\Net\Wechat($options); 	//创建实例对象
			setCache('weObj',$weObj);			 					
		};
		//$weObj->valid();
		//valid()明文或兼容模式可以在接口验证通过后注释此句，但加密模式一定不能注释，否则会验证失败
		
		$Openid=$weObj->getRev()->getRevFrom();

        $mEvent = $weObj->getRev()->getRevEvent();

        switch($mEvent['event']) {
            case \Org\Net\Wechat::EVENT_UNSUBSCRIBE:
            
			//取消关注事件
			//删除用户信息
			$mysql =new \SaeMysql();
			$sql = "DELETE FROM `score_users` WHERE `OpenID` = '" . $Openid . "'";
			
			$mysql->runSql($sql); 
			
			$mysql->closeDb();		
			if($mysql->errno() != 0 ){
				echo "系统发生错误，请联系管理员!";
			}
			
            break;
            case \Org\Net\Wechat::EVENT_SUBSCRIBE:
			//关注事件

            $news=array(
                "0"=>array(
                    'Title'=>'加入银狐体育，享受健康人生',
                    'Description'=>'银狐体育的梦想是让每个人都能享受到运动带来的快感和健康。拒绝沉闷，感受激情，美好人生，始于运动！',
                    'PicUrl'=>'http://mmbiz.qpic.cn/mmbiz/yBb5vu2S8bNgr3eiao05Xyd8ExRib0czskeUrXWKmRgwINwyjYDuibNZBL7tbqnZSjqJVLymPKqYoX100riawsBOYA/640?wx_fmt=jpeg&tp=webp&wxfrom=5',
                    'Url'=>'http://mp.weixin.qq.com/s?__biz=MzAwMDU2NzgwNQ==&mid=207251016&idx=1&sn=04cee09e32208fd0efc3f4ab19f5a1d7#rd'
                    ));
            $weObj->news($news)->reply(); 
			
			//保存用户信息
			$mysql =new \SaeMysql();
			$sql = "INSERT INTO `score_users`(`OpenID`) VALUES('" . $Openid . "')";
			
			$mysql->runSql($sql); 
			
			$mysql->closeDb();		
			if($mysql->errno() != 0 ){
				echo "系统发生错误，请联系管理员!";
			}

            break;
		}
        $customer_account='sis@sfssis';
        $kf=$weObj->getKFSession($Openid);
        if (!$kf){
             $weObj->createKFSession($Openid,$customer_account,'客服转接中，请稍候...');
        } else {
            $customer_account=$kf["kf_account"];
        }
        $weObj->transfer_customer_service($customer_account)->reply();
	}
}